import styles from './index.less';
import { useState, useEffect, useRef } from 'react';
import { history, Link, useIntl, useLocation } from 'umi';
import Highlighter from 'react-highlight-words';
import {
  Button,
  Table,
  Radio,
  Divider,
  Space,
  Drawer,
  Form,
  Select,
  Input,
  Switch,
  Row,
  Col,
  message,
  Popconfirm,
  Modal,
  Tag,
} from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import request from '@/utils/request';
import NoDataExplain from './components/explain';
import EditContact from '@/pages/components/editContact';
import { handleAvatarError } from '@/utils';
import { leadStagefn, leadSourcefn, priorityfn } from '@/data/options';

const LiaisonPage = function () {
  const intl = useIntl();

  const ulocation = useLocation();

  const tableMainRef = useRef();

  const leadStage = leadStagefn();
  const leadSource = leadSourcefn();
  const priority = priorityfn();

  const [createVisible, setCreateVisible] = useState(false);
  const [joinRosterVisible, setJoinRosterVisible] = useState(false);
  const [rosterName, setRosterName] = useState('');
  const [contactList, setContactList] = useState([]);
  const [rosterList, setRosterList] = useState([]);
  const [rowSelected, setRowSelected] = useState([]);
  const [newRostername, setNewRostername] = useState('');
  const [rosterSelected, setRosterSelected] = useState({});

  const [editUser, setEditUser] = useState({});

  const searchInputRef = useRef();
  const [searched, setSearched] = useState({
    text: String,
    column: Number,
  });

  const getColumnSearchProps = (dataIndex: any) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInputRef}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            Search
          </Button>
          <Button
            onClick={() => handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            Reset
          </Button>
          {/* <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({ closeDropdown: false });
              setSearched({
                text: selectedKeys[0],
                column: dataIndex,
              });
            }}
          >
            Filter
          </Button> */}
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase())
        : '',
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInputRef.current?.select(), 100);
      }
    },
    render: (text: string, record: any) =>
      searched.column === dataIndex ? (
        <div>
          <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
            searchWords={[searched.text]}
            autoEscape
            textToHighlight={text ? text.toString() : ''}
          />
        </div>
      ) : (
        <div>{text}</div>
      ),
  });

  const columns = [
    {
      title: intl.formatMessage({ id: 'avatar' }),
      width: 80,
      dataIndex: 'avatar',
      fixed: 'left',
      render: (text: string, record: any) => (
        <img
          src={record.image || ''}
          onError={handleAvatarError}
          alt=""
          className={styles.avatar}
        />
      ),
    },
    {
      title: intl.formatMessage({ id: 'name' }),
      width: 150,
      dataIndex: 'name',
      fixed: 'left',
      ...getColumnSearchProps('name'),
    },
    {
      title: intl.formatMessage({ id: 'label' }),
      width: 150,
      dataIndex: 'label',
      render: (text: string, record: any) => (
        <>
          {record.tagList && record.tagList.length
            ? record.tagList &&
              record.tagList.map((n) => <Tag color={n.color}>{n.tagName}</Tag>)
            : null}
        </>
      ),
    },
    {
      title: intl.formatMessage({ id: 'email' }),
      width: 150,
      dataIndex: 'email',
      ...getColumnSearchProps('email'),
    },
    {
      title: intl.formatMessage({ id: 'phonenumber' }),
      width: 150,
      dataIndex: 'phone',
    },
    {
      title: intl.formatMessage({ id: 'companyname' }),
      width: 150,
      dataIndex: 'companyName',
    },
    {
      title: intl.formatMessage({ id: 'jobtitle' }),
      width: 150,
      dataIndex: 'jobTitle',
    },
    {
      title: intl.formatMessage({ id: 'contactowner' }),
      width: 150,
      dataIndex: 'contactOwner',
    },
    {
      title: intl.formatMessage({ id: 'leadstage' }),
      width: 150,
      dataIndex: 'leadstage',
      render: (text: string, record: any) => (
        <div>{leadStage.find((n) => n.value === record.leadStage)?.label}</div>
      ),
    },
    {
      title: intl.formatMessage({ id: 'leadsource' }),
      width: 150,
      dataIndex: 'leadsource',
      render: (text: string, record: any) => (
        <div>
          {leadSource.find((n) => n.value === record.leadSource)?.label}
        </div>
      ),
    },
    {
      title: intl.formatMessage({ id: 'priority' }),
      width: 150,
      dataIndex: 'priority',
      render: (text: string, record: any) => (
        <div>{priority.find((n) => n.value === record.priority)?.label}</div>
      ),
    },
    // {
    //   title: intl.formatMessage({ id: 'country' }),
    //   width: 150,
    //   dataIndex: 'country',
    // },
    {
      title: intl.formatMessage({ id: 'subscriber' }),
      width: 150,
      dataIndex: 'subscriber',
      render: (text: string) => (
        <div>
          {text === 'Y'
            ? intl.formatMessage({ id: 'yes' })
            : intl.formatMessage({ id: 'no' })}
        </div>
      ),
    },
    {
      title: intl.formatMessage({ id: 'lastcontactfromyou' }),
      width: 150,
      dataIndex: 'lastContactFromYou',
    },
    {
      title: intl.formatMessage({ id: 'lastcontactfromcustomers' }),
      width: 180,
      dataIndex: 'lastContactFromCustomers',
    },
    {
      title: intl.formatMessage({ id: 'createDate' }),
      width: 150,
      dataIndex: 'createdDate',
    },
    {
      title: intl.formatMessage({ id: 'updateDate' }),
      width: 150,
      dataIndex: 'updatedDate',
    },
    {
      title: intl.formatMessage({ id: 'action' }),
      width: 200,
      dataIndex: 'action',
      fixed: 'right',
      render: (text: string, record: any) => (
        <div style={{ display: 'flex' }}>
          {record.isExists === 'Y' ? (
            <Button type="link" onClick={() => handleSend(record)}>
              {intl.formatMessage({ id: 'send' })}
            </Button>
          ) : null}

          <Button type="link" onClick={() => openEditContact(record)}>
            {intl.formatMessage({ id: 'edit' })}
          </Button>
          <Popconfirm
            placement="bottomRight"
            title={intl.formatMessage({ id: 'RU_deletecontact' })}
            onConfirm={() => onRemove(record)}
            okText={intl.formatMessage({ id: 'yes' })}
            cancelText={intl.formatMessage({ id: 'no' })}
          >
            <Button type="link">{intl.formatMessage({ id: 'remove' })}</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  // rowSelection object indicates the need for row selection
  const rowSelection = {
    selectedRowKeys: rowSelected.map((n) => n.id),
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      setRowSelected(selectedRows);
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  const onOpen = () => {
    setEditUser({});
    setCreateVisible(true);
  };
  const onClose = () => {
    setCreateVisible(false);
  };

  const getList = () => {
    request.get('/contact/get').then((res) => {
      setContactList(res.data.contactList || []);
    });
  };
  const getListRoster = () => {
    request.get('/roster/get').then((res) => {
      setRosterList(res.data.rosterList || []);
    });
  };

  useEffect(() => {
    getList();
    getListRoster();
  }, []);

  const handleSend = (record: any) => {
    history.push(`/inbox?chatId=${record.chatId}`);
  };

  const onRemove = (record: any) => {
    request.delete(`/contact/${record.id}`).then((res) => {
      message.success(intl.formatMessage({ id: 'removesuccess' }));
      getList();
    });
  };

  const openEditContact = (record: any) => {
    setEditUser(record);
    setCreateVisible(true);
  };

  const onOpenJoinRoster = () => {
    if (ulocation.query.rosterId) {
      onSubmitJoinRoster();
      return;
    }
    setJoinRosterVisible(true);
  };
  const onCloseJoinRoster = () => {
    setJoinRosterVisible(false);
  };
  const onSubmitJoinRoster = () => {
    if (rosterName || rowSelected.length) {
      const contactId = rowSelected.map((n: any) => n.id);
      console.log('contactId', contactId, rosterSelected);
      const data: any = {
        contactId, //联系人id :contact.id
      };
      if (ulocation.query.rosterId) {
        data.rosterId = ulocation.query.rosterId * 1;
      } else {
        if (rosterSelected.id) {
          data.rosterId = rosterSelected.id;
        } else {
          data.rosterName = rosterSelected.rosterName;
        }
      }

      request.post('/rosterUser/create', data).then((res) => {
        message.success(intl.formatMessage({ id: 'addsuccess' }));
        onCloseJoinRoster();
        getList();
        setRowSelected([]);
        if (ulocation.query.rosterId) {
          history.goBack();
        }
      });
    }
  };

  const onNameChange = (e: any) => {
    const { value } = e.target;
    setNewRostername(value);
  };

  const addItem = () => {
    if (newRostername) {
      setRosterList([...rosterList, { rosterName: newRostername }]);
      setNewRostername('');
    }
  };

  const onSelectRoster = (value: any, e: any) => {
    setRosterSelected(rosterList[e.key]);
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearched({
      text: selectedKeys[0],
      column: dataIndex,
    });
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearched({
      ...searched,
      text: '',
    });
  };

  return (
    <div className={styles.rosterContainer}>
      {/* <div className={styles.left}>
        <div className={styles.title}>
          {intl.formatMessage({ id: 'contacts' })}
        </div>
        <div className={styles.subtitle}>
          {contactList.length} {intl.formatMessage({ id: 'contacts_s' })}
        </div>
      </div> */}
      <div className={styles.right}>
        <div className={styles.ccHead}>
          {/* <div className={styles.ccHeadTitle}>
            {contactList.length} {intl.formatMessage({ id: 'contacts_s' })}
          </div> */}
          <span></span>
          <Space>
            {/* <Button type="primary" onClick={onOpen}>编辑资料栏</Button> */}
            {rowSelected.length ? (
              <Button type="primary" onClick={onOpenJoinRoster}>
                {intl.formatMessage({ id: 'addToRoster' })}
              </Button>
            ) : (
              ''
            )}

            {/* <Button onClick={onExport}>
              {intl.formatMessage({ id: 'import' })}
            </Button> */}
            <Button type="primary" onClick={onOpen}>
              {intl.formatMessage({ id: 'create' })}
            </Button>
          </Space>
        </div>
        <div className={styles.ccTable}>
          <div className={styles.tablemain} ref={tableMainRef}>
            <Table
              className={`${styles.liaisonTable}, nodatanoshow`}
              rowKey="id"
              rowSelection={{
                type: 'checkbox',
                ...rowSelection,
              }}
              scroll={{
                x: '100%',
                y: tableMainRef.current
                  ? tableMainRef.current.clientHeight - 140
                  : 610,
              }}
              columns={columns}
              dataSource={contactList}
              pagination={{
                showTotal: (total) =>
                  `${intl.formatMessage({ id: 'total' })}: ${total}`,
              }}
            />
            {!contactList.length ? (
              <div className={styles.nodatacon}>
                <NoDataExplain />
              </div>
            ) : (
              ''
            )}
          </div>
        </div>
      </div>
      <EditContact
        visible={createVisible}
        onClose={onClose}
        user={editUser}
        getList={getList}
      />
      <Modal
        title={intl.formatMessage({ id: 'joinRoster' })}
        visible={joinRosterVisible}
        onOk={onSubmitJoinRoster}
        onCancel={onCloseJoinRoster}
      >
        <Select
          style={{ width: 240 }}
          placeholder={intl.formatMessage({ id: 'selectRosterName' })}
          onSelect={onSelectRoster}
          dropdownRender={(menu) => (
            <div>
              {menu}
              <Divider style={{ margin: '4px 0' }} />
              <div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}>
                <Input
                  style={{ flex: 'auto' }}
                  value={newRostername}
                  onChange={onNameChange}
                />
                <a
                  style={{
                    flex: 'none',
                    padding: '8px',
                    display: 'block',
                    cursor: 'pointer',
                  }}
                  onClick={addItem}
                >
                  <PlusOutlined /> {intl.formatMessage({ id: 'addItem' })}
                </a>
              </div>
            </div>
          )}
        >
          {rosterList.map(
            (r: { id: number; rosterName: string }, i: number) => (
              <Select.Option key={i} value={r.id}>
                {r.rosterName}
              </Select.Option>
            ),
          )}
        </Select>
      </Modal>
    </div>
  );
};

LiaisonPage.title = '联络人';

export default LiaisonPage;
